package api

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"
	"weiboxs.com/new_h_glasses/enums"
	"weiboxs.com/new_h_glasses/models"
	"weiboxs.com/new_h_glasses/services"
	"weiboxs.com/new_h_glasses/utils"
)

type ApiEquipmentController struct {
	ApiBaseController
}

// 获取检查数据
func (c *ApiEquipmentController) Getequipment() {
	if c.Ctx.Input.IsPost() {
		archives_id, _ := c.GetInt64("archives_id")
		var err error
		var archives *models.Archives
		if archives_id > 0 {
			archives, err = models.GetArchivesById(archives_id) //ID号查询
			if archives.Id == 0 {
				err = errors.New("档案信息不存在")
			}
		} else {
			c.jsonResult(enums.JRCodeFailed, "参数错误", "")
		}

		listDate := make([]interface{}, 0)
		listData := make(map[string]*models.EquipmentData, 0)
		nowDate := utils.GetDate(time.Now().Unix())

		listDate = append(listDate, nowDate)
		//设置默认值
		if err != nil { //等于0只返回空值
			c.jsonResult(enums.JRCodeSucc, "ok", map[string]interface{}{"list_date": listDate, "list_data": listData})
			return
		}
		equipments, _ := models.GetEquipmentDataByArchives(archives.Id)
		if len(equipments) > 0 {
			for k, _ := range equipments {
				value := equipments[k]
				intoDate := utils.GetDate(value.CreatedAt)
				if _, ok := listData[intoDate]; !ok { //不存在则添加
					if nowDate != intoDate { //非当天的增加日期列表
						listDate = append(listDate, intoDate)
					}
					listData[intoDate] = value
				}
			}
			c.jsonResult(enums.JRCodeSucc, "ok", map[string]interface{}{"list_date": listDate, "list_data": listData})
		} else {
			c.jsonResult(enums.JRCodeSucc, "ok", map[string]interface{}{"list_date": listDate, "list_data": listData})
			return
		}
	}
}

// 验证数据是否存在
func (c *ApiEquipmentController) EqCheckdata() {

}

// 保存数据
func (c *ApiEquipmentController) Eqsavedata() {
	if c.Ctx.Input.IsPost() {
		archives_id, _ := c.GetInt64("archives_id")
		if archives_id == 0 {
			c.jsonResult(enums.JRCodeFailed, "保存失败：用户信息为空", "")
		}
		data := c.GetString("data")
		if len(data) == 0 {
			c.jsonResult(enums.JRCodeFailed, "保存失败：检查数据为空", "")
		}
		start := utils.GetDateParse(utils.GetDate(time.Now().Unix()))
		end := start + 80000
		ser := services.EquipmentService{}
		if err := ser.Eqsavedata(archives_id, data, start, end, c.curUser); err != nil {
			c.jsonResult(enums.JRCodeFailed, err.Error(), "")
		}
		c.jsonResult(enums.JRCodeSucc, "保存成功", "")
	}
}

// 调取患者验光数据
func (c *ApiEquipmentController) OptometryDataLists() {
	if c.Ctx.Input.IsPost() {
		mz_code := c.GetString("mz_code")
		if len(mz_code) == 0 {
			c.jsonResult(enums.JRCodeFailed, "参传错误", "")
		}
		var params models.OptometryQueryParam
		lists := models.OptometryList(&params)
		if len(lists) > 0 {
			for k, _ := range lists {
				lists[k].Archives = nil
				lists[k].CreatedBy = fmt.Sprintf("%s / %s", utils.GetDate(lists[k].CreatedAt), lists[k].CreatedBy)
				lists[k].ChufangData = models.GetOptometryDataList(lists[k].Id)
			}
		}
		c.jsonResult(enums.JRCodeSucc, "ok", lists)
	}
	c.jsonResult(enums.JRCodeFailed, "参数错误", "")
}

// 处理日期
func (c *ApiEquipmentController) GetTimeParse(times string) int64 {
	if "" == times {
		return 0
	}
	loc, _ := time.LoadLocation("Local")
	parse, _ := time.ParseInLocation("2006-01-02 15:04:05", times, loc)
	return parse.Unix()
}

// 输出总览数据
type eyeType struct {
	Left  map[string]float64 `json:"left"`
	Right map[string]float64 `json:"right"`
}

type overViewStruct struct { //总览数据
	Vision     eyeType `json:"vision"`     //裸眼视力
	Correct    eyeType `json:"correct"`    //矫正视力
	Axial      eyeType `json:"axial"`      //眼轴
	Pressure   eyeType `json:"pressure"`   //眼压
	Archheight eyeType `json:"archheight"` //拱高
	SE         eyeType `json:"se"`         //等效球镜
}

func (c *ApiEquipmentController) GetOverView() {
	archives_id, _ := c.GetInt64("archives_id", 0)
	if archives_id == 0 {
		c.jsonResult(enums.JRCodeFailed, "参数为空", "")
	}
	//查询检查数据
	equipments, _ := models.GetEquipmentDataByArchives(archives_id)
	if len(equipments) == 0 {
		c.jsonResult(enums.JRCodeFailed, "没有检查数据可分析", "")
	}

	//初始化函数
	var initMap = func() eyeType {
		e := eyeType{}
		e.Left = make(map[string]float64)
		e.Right = make(map[string]float64)
		return e
	}

	//初始化数据集合
	overView := new(overViewStruct)
	overView.Vision = initMap()
	overView.Correct = initMap()
	overView.Axial = initMap()
	overView.Pressure = initMap()
	overView.Archheight = initMap()
	overView.SE = initMap()

	for k, _ := range equipments {
		if k >= 5 {
			continue
		}
		value := equipments[k]
		timeValue := utils.GetDateFormat(value.CreatedAt, "06/01/02")
		//祼眼视力
		if len(value.RightVision) > 0 {
			overView.Vision.Right[timeValue] = c.parse_float(value.RightVision)
			overView.Vision.Left[timeValue] = c.parse_float(value.LeftVision)
		}
		//矫正视力
		if len(value.RightCorrectVision) > 0 {
			overView.Correct.Right[timeValue] = c.parse_float(value.RightCorrectVision)
			overView.Correct.Left[timeValue] = c.parse_float(value.LeftCorrectVision)
		}
		//眼轴
		if len(value.EyeRightAxial) > 0 {
			overView.Axial.Right[timeValue] = c.parse_float(value.EyeRightAxial)
			overView.Axial.Left[timeValue] = c.parse_float(value.EyeLeftAxial)
		}
		//眼压
		if len(value.RightPressure) > 0 {
			overView.Pressure.Right[timeValue] = c.parse_float(value.RightPressure)
			overView.Pressure.Left[timeValue] = c.parse_float(value.LeftPressure)
		}
		if len(value.RightBallDiameter) > 0 && len(value.LeftBallDiameter) > 0 {
			overView.SE.Right[timeValue] = c.parse_se(value.RightBallDiameter, value.RightColumnDiameter)
			overView.SE.Left[timeValue] = c.parse_se(value.LeftBallDiameter, value.LeftColumnDiameter)
		}
	}

	c.jsonResult(enums.JRCodeSucc, "", overView)
}

// 转换值为数值型
func (c *ApiEquipmentController) parse_float(value string) float64 {
	valueNumber, _ := strconv.ParseFloat(strings.TrimSuffix(value, "-"), 64)
	return valueNumber
}

// 计算等效球镜
func (c *ApiEquipmentController) parse_se(q, z string) float64 {
	qNumber, _ := strconv.ParseFloat(strings.TrimSuffix(q, "-"), 64)
	zNumber, _ := strconv.ParseFloat(strings.Replace(strings.Replace(z, "-", "", -1), "+", "", -1), 64)
	zNumber = zNumber / 2 //柱镜的一半
	if qNumber >= 0 {
		qNumber = qNumber + zNumber
	} else {
		qNumber = qNumber - zNumber
	}
	value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", qNumber), 64)
	return value
}
